package io.github.eric.urpc.core.rpc;

import io.github.eric.urpc.core.exception.UrpcMsgRegException;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MessageRegistrar {

	//msgType -> msgInfo
	private final Map<String, MessageInfo> msgTypeToMsgInfo = new HashMap<>();

	void registerCallback(Class<?> clazz, RpcController service, Method method, int rpcContextIndex) {
		try {
			if (msgTypeToMsgInfo.containsKey(clazz.getName())) {
				throw new UrpcMsgRegException(String.format("[urpc] duplicate rpc method, msg type '%s', current in: '%s', already in: '%s'",
						clazz.getName(), service.getClass().getName(), msgTypeToMsgInfo.get(clazz.getName()).getService().getClass().getName()));
			}
			MessageInfo messageInfo = new MessageInfo();
			messageInfo.setClassType(clazz);
			messageInfo.setService(service);
			messageInfo.setMethod(method);
			messageInfo.setRpcContextIndex(rpcContextIndex);
			msgTypeToMsgInfo.put(clazz.getName(), messageInfo);
		} catch (UrpcMsgRegException e) {
			throw e;
		} catch (Exception e) {
			throw new UrpcMsgRegException("[urpc] message registration error", e);
		}
	}

	public MessageInfo getMessageInfo(Class<?> clazz) {
		return getMessageInfo(clazz.getName());
	}

	public MessageInfo getMessageInfo(String className) {
		return msgTypeToMsgInfo.get(className);
	}
}
